package com.resou.reader.bookshelf.bookedit.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;
import com.resou.reader.R;
import com.resou.reader.bookshelf.bookedit.BookShelfEditActivity;
import com.resou.reader.bookshelf.bookedit.adapter.BookShelfEditAdapter.ViewHolder;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by ${Garrett} on 2018/9/7.
 * Contact me krouky@outlook.com
 */
public class BookShelfEditAdapter extends RecyclerView.Adapter<ViewHolder> {
    private List<BookCollection> mBookList;

    private OnItemSelectedListener mSelectedListener;

    private boolean isSelectedAll;

    private Set<BookCollection> mSelectedBook = new HashSet<>();
    private BookShelfEditActivity mActivity;

    public BookShelfEditAdapter(OnItemSelectedListener selectedListener) {
        mSelectedListener = selectedListener;
        mActivity = (BookShelfEditActivity) selectedListener;
        mBookList = new ArrayList<>();
    }

    public void setBookList(List<BookCollection> list) {
        mBookList = list;
        notifyDataSetChanged();
    }

    public List<BookCollection> getBookList() {
        return mBookList;
    }

    public boolean isSelectedAll() {
        return isSelectedAll;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    int position = -1;

    /**
     * 删除书本
     */
    public void deleteSelectedItems() {
        Set<BookCollection> collections = new HashSet<>();
        for (Iterator iterator = mSelectedBook.iterator(); iterator.hasNext(); ) {
            BookCollection selected = (BookCollection) iterator.next();
            int selectedIndex = mBookList.indexOf(selected);
            mBookList.remove(selectedIndex);
            collections.add(selected);
//            mSelectedListener.onItemDeleted(selected);
            notifyItemRemoved(selectedIndex);
        }

        mSelectedListener.onItemsDeleted(collections);
        mSelectedBook.clear();
//        mSelectedListener.onItemsDeleted(mSelectedBook);
    }

    private static final String TAG = "BookShelfEditAdapter";

    /**
     * 全选
     *
     * @param selectedAll
     */
    public void setSelectedAll(boolean selectedAll) {
        isSelectedAll = selectedAll;
        if (selectedAll) {
            //                if (mSelectedBook.contains(book)) {
            //                    continue;
            //                }
            mSelectedBook.addAll(mBookList);
        } else {
            inverseSelection();
        }
        notifyDataSetChanged();
    }

    /**
     * 反选
     */
    public void inverseSelection() {
        for (BookCollection collection : mBookList) {
            if (mSelectedBook.contains(collection)) {
                mSelectedBook.remove(collection);
            } else {
                mSelectedBook.add(collection);
            }
        }
    }

    public void clearSelected() {
        mSelectedBook.clear();
    }

    public int getSelectedItemCount() {
        return mSelectedBook.size();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.book_shelf_list_item, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int i) {
        BookCollection collection = mBookList.get(i);

        if (i == position && position != -1) {
            mSelectedBook.add(collection);
            holder.ivChooseStatus.setSelected(true);
        }


        Glide.with(holder.itemView).setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_RGB_565)).load(collection.getPicUrl()).into(holder.ivCover);
        holder.tvBookName.setText(collection.getName());
        holder.tvReadingStatus.setText(collection.getHistoryChapterName());
        if (mActivity.isInEditMode) {
            holder.ivChooseStatus.setVisibility(View.VISIBLE);
            holder.ivShade.setVisibility(View.VISIBLE);
            if (mSelectedBook.contains(collection)) {
                holder.ivChooseStatus.setSelected(true);
            } else {
                holder.ivChooseStatus.setSelected(false);
            }
        } else {
            holder.ivShade.setVisibility(View.GONE);
            holder.ivChooseStatus.setVisibility(View.GONE);
        }
        holder.itemView.setOnClickListener(v -> {
            if (mActivity.isInEditMode) {
                if (holder.ivChooseStatus.isSelected()) {
                    //已选择，点击后从已选列表中删除
                    holder.ivChooseStatus.setSelected(false);
                    mSelectedBook.remove(collection);
                    mSelectedListener.onItemSelected();
                } else {
                    //未选择，点击后添加到已选列表
                    holder.ivChooseStatus.setSelected(true);
                    mSelectedBook.add(collection);
                    mSelectedListener.onItemSelected();
                }
            } else {
                mSelectedListener.onItemClicked(collection);
            }
        });

    }

    @Override
    public int getItemCount() {
        return mBookList == null ? 0 : mBookList.size();
    }


    class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_cover)
        ImageView ivCover;
        @BindView(R.id.iv_shade)
        ImageView ivShade;
        @BindView(R.id.iv_choose_status)
        ImageView ivChooseStatus;
        @BindView(R.id.card_view)
        CardView cardView;
        @BindView(R.id.tv_book_name)
        TextView tvBookName;
        @BindView(R.id.tv_reading_status)
        TextView tvReadingStatus;
        @BindView(R.id.book_shelf_item_group)
        FrameLayout bookShelfItemGroup;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface OnItemSelectedListener {
        void onItemSelected();

        void onItemDeleted(BookCollection collection);

        void onItemsDeleted(Set<BookCollection> collections);

        void onItemClicked(BookCollection collection);
    }
}
